from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import Boolean, DateTime, Integer, String, Text, func, ForeignKey, Enum
from sqlalchemy.orm import Mapped, mapped_column, relationship
import enum

from app.models.base import Base


class MessageRole(enum.Enum):
    """消息角色枚举"""
    USER = "user"
    ASSISTANT = "assistant"
    SYSTEM = "system"


class ChatMode(enum.Enum):
    """聊天模式枚举"""
    NORMAL = "normal"
    AGENT = "agent"


class Conversation(Base):
    """对话表"""
    __tablename__ = "conversations"

    # Primary key
    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    
    # 对话标题
    title: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    
    # 用户ID（可选，如果需要用户关联）
    user_id: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
    
    # 对话状态
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    
    # 消息总数
    message_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    
    # 聊天模式
    chat_mode: Mapped[ChatMode] = mapped_column(
        Enum(ChatMode), 
        default=ChatMode.NORMAL, 
        nullable=False
    )
    
    # 最后活跃时间
    last_activity_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False
    )
    
    # Timestamps
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), 
        server_default=func.now(),
        nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False
    )
    
    # 关系
    messages: Mapped[list["Message"]] = relationship("Message", back_populates="conversation", cascade="all, delete-orphan")
    summaries: Mapped[list["ConversationSummary"]] = relationship("ConversationSummary", back_populates="conversation", cascade="all, delete-orphan")

    def __repr__(self) -> str:
        return f"<Conversation(id={self.id}, title='{self.title}', message_count={self.message_count})>"


class Message(Base):
    """消息表"""
    __tablename__ = "messages"

    # Primary key
    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    
    # 对话ID
    conversation_id: Mapped[int] = mapped_column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
    
    # 消息角色
    role: Mapped[MessageRole] = mapped_column(Enum(MessageRole), nullable=False)
    
    # 消息内容
    content: Mapped[str] = mapped_column(Text, nullable=False)
    
    # 消息在对话中的序号
    sequence_number: Mapped[int] = mapped_column(Integer, nullable=False)
    
    # 消息元数据（JSON格式，存储额外信息）
    message_metadata: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    
    # Timestamps
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), 
        server_default=func.now(),
        nullable=False
    )
    
    # 关系
    conversation: Mapped["Conversation"] = relationship("Conversation", back_populates="messages")

    def __repr__(self) -> str:
        return f"<Message(id={self.id}, conversation_id={self.conversation_id}, role={self.role.value}, seq={self.sequence_number})>"


class ConversationSummary(Base):
    """对话摘要表"""
    __tablename__ = "conversation_summaries"

    # Primary key
    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    
    # 对话ID
    conversation_id: Mapped[int] = mapped_column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
    
    # 摘要内容
    summary_content: Mapped[str] = mapped_column(Text, nullable=False)
    
    # 摘要覆盖的消息范围（起始序号）
    start_message_seq: Mapped[int] = mapped_column(Integer, nullable=False)
    
    # 摘要覆盖的消息范围（结束序号）
    end_message_seq: Mapped[int] = mapped_column(Integer, nullable=False)
    
    # 摘要类型（可以是阶段性摘要或完整摘要）
    summary_type: Mapped[str] = mapped_column(String(50), default="partial", nullable=False)
    
    # 是否为当前有效摘要
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    
    # Timestamps
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), 
        server_default=func.now(),
        nullable=False
    )
    
    # 关系
    conversation: Mapped["Conversation"] = relationship("Conversation", back_populates="summaries")

    def __repr__(self) -> str:
        return f"<ConversationSummary(id={self.id}, conversation_id={self.conversation_id}, type={self.summary_type}, seq={self.start_message_seq}-{self.end_message_seq})>"